package com.bsy.network.adapter

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type


/**
 * Created by Sincerity on 2022/8/10.
 * Copyright
 * 描述：自定义类型转换器 主要处理BaseResponse 中泛型T的问题
 */
class GsonDConverterFactory private constructor(gson: Gson?) : Converter.Factory() {
    private val gson: Gson

    init {
        if (gson == null) throw NullPointerException("gson == null")
        this.gson = gson
    }

    override fun responseBodyConverter(
        type: Type, annotations: Array<out Annotation>, retrofit: Retrofit
    ): Converter<ResponseBody, *> {
        return GsonResponseBodyConverter<Any>(gson, type)
    }

    override fun requestBodyConverter(
        type: Type,
        parameterAnnotations: Array<out Annotation>,
        methodAnnotations: Array<out Annotation>,
        retrofit: Retrofit
    ): Converter<*, RequestBody> {
        val adapter = gson.getAdapter(TypeToken.get(type))
        return GsonRequestBodyConverter(gson, adapter)
    }

    companion object {
        @JvmOverloads
        fun create(gson: Gson? = Gson()): GsonDConverterFactory {
            return GsonDConverterFactory(gson)
        }
    }


}